package cn.id68.www.http.request;

import java.io.File;
import java.util.Map;

import cn.id68.www.http.callback.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2017/3/21.
 */
public class PostFileRequest extends OkHttpRequest {

    private static MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream");
    private File file;
    private MediaType mediaType;

    public PostFileRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, int id, File file, MediaType mediaType) {
        super(url, tag, params, headers, id);
        this.file = file;
        this.mediaType = mediaType;

        if (this.file == null){
            throw new NullPointerException("the file can not be null !");
        }
        if (mediaType == null){
            this.mediaType = MEDIA_TYPE_STREAM;
        }

    }

    @Override
    protected RequestBody buildRequestBody() {
        return RequestBody.create(mediaType,file);
    }

    @Override
    protected RequestBody wraRequestBody(RequestBody requestBody, final Callback callback) {

        if (callback == null){
            return requestBody;
        }

        CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener() {
            @Override
            public void onRequestProgress(long byteWritten, long contentLength) {
                callback.intProgress(byteWritten * 1.0f / contentLength,contentLength,id);
            }
        });

        return countingRequestBody;
    }

    @Override
    protected Request buildRequest(RequestBody requestBody) {
        return builder.post(requestBody).build();
    }
}
